<script setup lang='ts'>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { useGetMemberPageList, useUpdateMemberStatus } from '@fl/api/man-api'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'

import AddOrEdit from './add-or-edit.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/operations-pages/member/info',
})

const STATUS_LIST: any[] = []

STATUS_LIST.unshift({ label: '会员列表', value: '' })

const activeName = ref(STATUS_LIST[0].value)

const initialState = {
    enterpriseName: '',
}

const state = ref(cloneDeep(initialState))

const columns = [
    {
        label: '公司名称',
        prop: 'enterpriseName',
        renderField: (_, onChange) => {
            return h(ElInput, {
                onChange,
                onKeydown: (event: any) => {
                    if (event.key === 'Enter') {
                        event.preventDefault()
                    }
                },
            })
        },
        valueType: 'Input',
    },
]

const id = ref<any>('')

const form = ref<any>('')

const visible = ref<boolean>(false)

const STATUS_DICT = {
    0: '正常',
    1: '已过期',
    2: '已禁用',
}

const gridOptions = computed<VxeGridProps>(() => {
    return {
        columns: [
            { fixed: 'left', title: '序号', type: 'seq', width: 50 },
            { field: 'enterpriseName', minWidth: 180, title: '企业名称' },
            { field: 'memberLevelName', minWidth: 150, title: '会员等级' },
            { field: 'applyTime', minWidth: 150, title: '申请时间' },
            { field: 'effectiveTime', minWidth: 150, title: '生效时间' },
            { field: 'expirationTime', minWidth: 150, title: '有效期至' },
            {
                field: 'status',
                formatter: (row: any) => {
                    return STATUS_DICT[row.cellValue]
                },
                minWidth: 100,
                title: '状态',
            },
            { field: 'sourceName', minWidth: 120, title: '来源' },
            { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 300 },
        ],
        height: 700,
        toolbarConfig: {
            slots: {
                buttons: 'toolbar_buttons',
            },
        },
    }
})

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const params = computed(() => {
    return {
        enterpriseName: state.value.enterpriseName,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    }
})

const { data, isLoading } = useGetMemberPageList(params)

const { isPending: updateStatusLoading, mutate: updateStatusMutate } = useUpdateMemberStatus()

const loading = computed(() => isLoading.value || updateStatusLoading.value)

const tableData = ref<any[]>([])

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function showAdd() {
    visible.value = true
}

function showEdit(row: any) {
    id.value = row.memberId
    form.value = cloneDeep({ enterpriseId: row.enterpriseId, enterpriseName: row.enterpriseName, memberLevelId: row.memberLevelId, memberLevelName: row.memberLevelName })
    visible.value = true
}
function search(val: any) {
    state.value = cloneDeep(val)
    tablePage.value.currentPage = 1
}

function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value.currentPage = 1
}

function deactivated(row: any) {
    const params = {
        memberId: row.memberId,
        status: 2,
    }
    updateStatus(params)
}

function enabled(row: any) {
    const params = {
        memberId: row.memberId,
        status: 0,
    }
    updateStatus(params)
}

function updateStatus(params: any) {
    updateStatusMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value.records || [])
        tablePage.value.total = data.value.total ?? 0
    }
})
</script>

<template>
    <el-card shadow="never"
             mb-20
    >
        <div mb-20
             text-16
             font-700
        >
            会员信息管理
        </div>

        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="查询"
                    class="mb-20"
                    @submit="search"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <el-tabs v-model="activeName">
            <el-tab-pane v-for="item in STATUS_LIST"
                         :key="item.label"
                         :label="item.label"
                         :name="item.value"
            />
        </el-tabs>

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                     :loading="loading"
                     :data="tableData"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <div flex
                     w-full
                     justify-end
                >
                    <el-button type="primary"
                               @click="showAdd"
                    >
                        新建
                    </el-button>
                </div>
            </template>

            <template #operate="{ row }">
                <el-button v-if="STATUS_DICT[row.status] === '正常'"
                           text
                           type="primary"
                           @click="deactivated(row)"
                >
                    停用
                </el-button>

                <el-button v-if="STATUS_DICT[row.status] === '已禁用'"
                           text
                           type="primary"
                           @click="enabled(row)"
                >
                    启用
                </el-button>

                <el-button v-if="STATUS_DICT[row.status] === '正常' || STATUS_DICT[row.status] === '已过期'"
                           text
                           type="primary"
                           @click="showEdit(row)"
                >
                    续费
                </el-button>
            </template>
        </SearchTable>
    </el-card>

    <AddOrEdit :key="id"
               v-model:visible="visible"
               v-model:id="id"
               v-model:form="form"
    />
</template>
